<script setup>
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  energyData: {
    type: Object,
    default: () => ({
      electricity: 0,
      water: 0,
      gas: 0
    })
  }
})

// 图表实例
let electricityChart = null
let waterChart = null
let gasChart = null

// DOM引用
const electricityRef = ref(null)
const waterRef = ref(null)
const gasRef = ref(null)

// 初始化图表，添加延迟确保DOM已渲染
const initCharts = () => {
  // 清理现有图表
  if (electricityChart) electricityChart.dispose()
  if (waterChart) waterChart.dispose()
  if (gasChart) gasChart.dispose()
  
  // 使用nextTick和setTimeout双重保证DOM已渲染
  nextTick(() => {
    setTimeout(() => {
      try {
        // 初始化电力仪表盘
        if (electricityRef.value && electricityRef.value.clientWidth > 0) {
          electricityChart = echarts.init(electricityRef.value)
          electricityChart.setOption({
            series: [{
              type: 'gauge',
              center: ['50%', '60%'],
              radius: '85%',
              min: 0,
              max: 10000,
              startAngle: 210,
              endAngle: -30,
              axisLine: {
                lineStyle: {
                  width: 10,
                  color: [
                    [0.3, '#91c7ae'],
                    [0.7, '#4992ff'],
                    [1, '#c23531']
                  ]
                }
              },
              pointer: {
                itemStyle: {
                  color: '#ffffff'
                },
                width: 5
              },
              axisTick: {
                distance: -10,
                length: 8,
                lineStyle: {
                  color: '#fff',
                  width: 1
                }
              },
              splitLine: {
                distance: -16,
                length: 16,
                lineStyle: {
                  color: '#fff',
                  width: 2
                }
              },
              axisLabel: {
                distance: -26,
                color: '#fff',
                fontSize: 10,
                formatter: function(value) {
                  if (value % 2000 === 0) {
                    return value.toString();
                  }
                  return '';
                }
              },
              detail: {
                show: false
              },
              data: [{
                value: props.energyData?.electricity || 0
              }]
            }]
          })
        }
        
        // 初始化水量仪表盘
        if (waterRef.value && waterRef.value.clientWidth > 0) {
          waterChart = echarts.init(waterRef.value)
          waterChart.setOption({
            series: [{
              type: 'gauge',
              center: ['50%', '60%'],
              radius: '85%',
              min: 0,
              max: 40000,
              startAngle: 210,
              endAngle: -30,
              axisLine: {
                lineStyle: {
                  width: 10,
                  color: [
                    [0.3, '#91c7ae'],
                    [0.7, '#4992ff'],
                    [1, '#c23531']
                  ]
                }
              },
              pointer: {
                itemStyle: {
                  color: '#ffffff'
                },
                width: 5
              },
              axisTick: {
                distance: -10,
                length: 8,
                lineStyle: {
                  color: '#fff',
                  width: 1
                }
              },
              splitLine: {
                distance: -16,
                length: 16,
                lineStyle: {
                  color: '#fff',
                  width: 2
                }
              },
              axisLabel: {
                distance: -26,
                color: '#fff',
                fontSize: 10,
                formatter: function(value) {
                  if (value % 8000 === 0) {
                    return value.toString();
                  }
                  return '';
                }
              },
              detail: {
                show: false // 隐藏仪表盘中间的数字
              },
              data: [{
                value: props.energyData?.water || 0
              }]
            }]
          })
        }
        
        // 初始化气体消耗仪表盘
        if (gasRef.value && gasRef.value.clientWidth > 0) {
          gasChart = echarts.init(gasRef.value)
          gasChart.setOption({
            series: [{
              type: 'gauge',
              center: ['50%', '60%'],
              radius: '85%',
              min: 0,
              max: 100000,
              startAngle: 210,
              endAngle: -30,
              axisLine: {
                lineStyle: {
                  width: 10,
                  color: [
                    [0.3, '#F5E68C'],
                    [0.7, '#E6A23C'],
                    [1, '#F56C6C']
                  ]
                }
              },
              pointer: {
                itemStyle: {
                  color: '#ffffff'
                },
                width: 5
              },
              axisTick: {
                distance: -10,
                length: 8,
                lineStyle: {
                  color: '#fff',
                  width: 1
                }
              },
              splitLine: {
                distance: -16,
                length: 16,
                lineStyle: {
                  color: '#fff',
                  width: 2
                }
              },
              axisLabel: {
                distance: -26,
                color: '#fff',
                fontSize: 10,
                formatter: function(value) {
                  if (value % 20000 === 0) {
                    return (value/1000).toString()+'k';
                  }
                  return '';
                }
              },
              detail: {
                show: false // 隐藏仪表盘中间的数字
              },
              data: [{
                value: props.energyData?.gas || 0
              }]
            }]
          })
        }
      } catch (error) {
        console.error('初始化图表错误:', error)
      }
    }, 300)
  })
}

// 监听数据变化
watch(() => props.energyData, () => {
  nextTick(() => initCharts())
}, { deep: true })

// 窗口大小改变时重绘图表
const handleResize = () => {
  if (electricityChart) electricityChart.resize()
  if (waterChart) waterChart.resize()
  if (gasChart) gasChart.resize()
}

// 组件是否已卸载标志
let isMounted = true

onMounted(() => {
  isMounted = true
  // 确保DOM已经加载完成
  if (document.readyState === 'complete') {
    initCharts()
  } else {
    window.addEventListener('load', initCharts)
  }
  
  // 添加resize监听
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  isMounted = false
  window.removeEventListener('resize', handleResize)
  window.removeEventListener('load', initCharts)
  
  // 清理图表实例
  if (electricityChart) electricityChart.dispose()
  if (waterChart) waterChart.dispose()
  if (gasChart) gasChart.dispose()
  
  // 清空引用
  electricityChart = null
  waterChart = null
  gasChart = null
})
</script>

<template>
  <dv-border-box-8 class="dashboard-panel">
    <div class="panel-header">
      <i class="el-icon-lightning"></i>
      能源消耗监控
    </div>
    <div class="energy-gauge">
      <!-- 使用绝对定位调整位置确保在同一水平线 -->
      <div class="gauge-container">
        <div class="gauge-item">
          <div ref="electricityRef" class="gauge-chart"></div>
        </div>
        <div class="gauge-item">
          <div ref="waterRef" class="gauge-chart"></div>
        </div>
        <div class="gauge-item">
          <div ref="gasRef" class="gauge-chart"></div>
        </div>
      </div>
      
      <!-- 分离数值显示部分，使用固定布局确保对齐 -->
      <div class="gauge-values">
        <div class="gauge-value-item">
          <div class="gauge-value">{{ props.energyData?.electricity || 0 }}</div>
          <div class="gauge-name">耗电量</div>
        </div>
        <div class="gauge-value-item">
          <div class="gauge-value">{{ props.energyData?.water || 0 }}</div>
          <div class="gauge-name">耗水量</div>
        </div>
        <div class="gauge-value-item">
          <div class="gauge-value">{{ props.energyData?.gas || 0 }}</div>
          <div class="gauge-name">气体消耗</div>
        </div>
      </div>
    </div>
  </dv-border-box-8>
</template>

<style scoped>
.dashboard-panel {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}

.panel-header {
  font-size: 16px;
  color: #29b6ff;
  margin-bottom: 15px;
  padding-left: 10px;
}

.energy-gauge {
  display: flex;
  flex-direction: column;
  height: 90%;
}

.gauge-container {
  display: flex;
  width: 100%;
  height: 65%;
  margin-bottom: 10px;
}

.gauge-item {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.gauge-chart {
  width: 100%;
  height: 160px; /* 固定高度确保一致 */
}

/* 价值和标签布局 */
.gauge-values {
  display: flex;
  width: 100%;
  height: 35%;
  margin-top: 5px;
}

.gauge-value-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.gauge-value {
  font-size: 26px;
  font-weight: bold;
  color: #fff;
  text-shadow: 0 0 10px rgba(0, 255, 255, 0.8);
  margin-bottom: 8px;
}

.gauge-name {
  font-size: 16px;
  color: #fff;
  text-shadow: 0 0 8px rgba(0, 255, 255, 0.8);
  font-weight: bold;
}
</style> 